from lxml import etree

# xml = """
# <book>
#     <id>1</id>
#     <name>野花遍地香</name>
#     <price>1.23</price>
#     <nick>臭豆腐</nick>
#     <author>
#         <nick id="10086">周大强</nick>
#         <nick id="10010">周芷若</nick>
#         <nick class="joy">周杰伦</nick>
#         <nick class="jolin">蔡依林</nick>
#         <div>
#             <nick>惹了</nick>
#         </div>
#     </author>
#     <partner>
#         <nick id="ppc">胖胖陈</nick>
#         <nick id="ppbc">胖胖不陈</nick>
#     </partner>
# </book>
# """

# et = etree.XML(xml)
# res1 = et.xpath("/book")  # 开头的”/“表示根节点
# print(res1)
# res2=et.xpath("/book/name")  # 中间的”/“表示子节点
# print(res2)
# res3=et.xpath("/book/name/text()")  # text()取节点中的文本
# print(res3)

# res4 = et.xpath("/book//nick/text()")  # 取book中所有叫nick的子孙后代节点
# print(res4)
# res5 = et.xpath("/book/author/nick/text()")  # 取book子节点author中所有叫nick的子孙后代节点
# print(res5)
# res9 = et.xpath("/book/author/nick[1]/text()")  # 取book子节点author中第一个nick的子孙后代节点，注意下标表示第几个！
# print(res9)

# res5=et.xpath("/book//nick/text()")[0]  # 取book中第一个nick
# print(res5)

# 想要取出book两个子节点中author和partner中的nick
# 不想要book孙节点div中的nick
# 写成这样很麻烦
# res6=et.xpath("/book/author/nick/text()")
# print(res6)
# res6=et.xpath("/book/partner/nick/text()")
# print(res6)
# res6 = et.xpath("/book/*/nick/text()")  # * 通配符，只要是book的子节点，谁都行
# print(res6)
# res7 = et.xpath("/book//nick[@class='joy']/text()")  # 只要class为joy的nick节点， [@属性名='值']
# print(res7)
#
# res8 = et.xpath("/book//nick/@id")  # 取所有的id值
# print(res8)
#
# res9 = et.xpath("/book//nick/@id")[0]  # 取出一个id值
# print(res9)


html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Title</title>
</head>
<body>
    <ul>
        <li><a href="http://www.baidu.com">百度</a></li>
        <li><a href="http://www.google.com">谷歌</a></li>
        <li><a href="http://www.sogou.com">搜狗</a></li>
    </ul>
    <ol>
        <li><a href="feiji">飞机</a></li>
        <li><a href="dapao">大炮</a></li>
        <li><a href="huoche">火车</a></li>
    </ol>
    <div class="job">李嘉诚</div>
    <div class="common">胡辣汤</div>
</body>
</html>
"""

et = etree.HTML(html)
# ul_list = et.xpath("//ul/li[2]/a/text()")
# print(ul_list)
li_list = et.xpath("//li")
for li in li_list:
    href = li.xpath("./a/@href")  # ./表示当前节点。获取所有
    text = li.xpath("./a/text()")
    print(href,text)
    href = li.xpath("./a/@href")[0]  # 获取当前li节点下第一个符合条件的a标签的href属性值和文本内容
    text = li.xpath("./a/text()")[0]
    print(href,text)